package scene;

import geometrie.Point;
import geometrie.Transformation;

/**
 * Class that represents a facet in the 3D scenario. The facets are all
 * triangular and are represented by a set of three points which represents the
 * coordinates of each vertex of the this triangle.
 */
public class Facette3D {
	private Point[] vertices;
	private double altitude;

	/**
	 * Constructor for point from the point of vertex
	 * 
	 * @param v1
	 *            The point for the first vertex
	 * @param v2
	 *            The point for the second vertex
	 * @param v3
	 *            The point for the third vertex
	 */
	public Facette3D(Point v1, Point v2, Point v3) {
		vertices = new Point[3];
		vertices[0] = v1;
		vertices[1] = v2;
		vertices[2] = v3;
	}

	/**
	 * Constructor for a Facette3D from other given Facette3D
	 * 
	 * @param fct
	 *            The Facette3D
	 */
	public Facette3D(Facette3D fct) {
		this(fct.vertices[0], fct.vertices[1], fct.vertices[2]);
	}

	/**
	 * Get a specified vertex (1,2,3) of the Facette3D
	 * 
	 * @param index
	 *            The index of the vertex
	 * @return The point that represents this vertex. If a wrong index is given,
	 *         the method returns null.
	 */
	public Point getVertex(int index) {
		if (index > 3 || index < 1) {
			return null;
		}
		return vertices[index - 1];
	}

	/**
	 * Method to calculate the barycenter of a Facette3D
	 * 
	 * @return the barycenter's point
	 */
	private Point barycenter() {
		double xg, yg, zg;
		xg = (vertices[0].getXCartesien() + vertices[1].getXCartesien() + vertices[2]
				.getXCartesien()) / 3;
		yg = (vertices[0].getYCartesien() + vertices[1].getYCartesien() + vertices[2]
				.getYCartesien()) / 3;
		zg = (vertices[0].getZCartesien() + vertices[1].getZCartesien() + vertices[2]
				.getZCartesien()) / 3;
		return new Point(xg, yg, zg);
	}

	/**
	 * Apply a transformation in a specified Facette3D
	 * 
	 * @param t
	 *            the transformation to be applied
	 */
	public void applyTransformation(Transformation t) {
		vertices[0].applyTransformation(t);
		vertices[1].applyTransformation(t);
		vertices[2].applyTransformation(t);
	}

	@Override
	public String toString() {
		return "Facette3D [vertex1=" + vertices[0] + ", vertex2=" + vertices[1]
				+ ", vertex3=" + vertices[2] + "]" + "\n";
	}

	/**
	 * Method to set the altitude using the current value of the barycenter's Z
	 * coordinate.
	 */
	public void setAltitude() {
		altitude = barycenter().getZCartesien();
	}

	/**
	 * Method to get the current altitude
	 * 
	 * @return the altitude
	 */
	public double getAltitude() {
		return this.altitude;
	}
}
